import { fail } from './../../helper'
import { Injectable } from '@nestjs/common'
import { RegisterDto } from './dto/register.dto'
import { PrismaService } from '../common/prisma.service'
// 对密码进行 md5 加密
// import * as md5 from 'md5'
import { createHash } from 'crypto'
import { LoginDto } from './dto/login.dto'
import { JwtService } from '@nestjs/jwt'
import { User } from '@prisma/client'

@Injectable()
export class AuthService {
	constructor(private readonly prisma: PrismaService, private jwt: JwtService) {}

	private encrypt(password: string) {
		return createHash('md5').update(password).digest('hex')
	}

	private createToken(user: User) {
		return { token: this.jwt.sign({ id: user.id }) }
	}

	async register(dto: RegisterDto) {
		const user = await this.prisma.user.create({
			data: {
				...dto,
				// password: md5(dto.password)
				password: this.encrypt(dto.password)
			}
		})

		return this.createToken(user)
	}

	async login(dto: LoginDto) {
		const user = await this.prisma.user.findFirst({
			where: {
				OR: [{ username: dto.username }, { email: dto.username }, { mobile: dto.username }]
			}
		})

		// 验证密码是否一致
		if (user.password !== this.encrypt(dto.password)) {
			return fail('password', '密码验证错误')
		}

		// TODO 设置 token
		return this.createToken(user)
	}
}
